package cn.geminis.crypto.core.x509;

import cn.geminis.crypto.core.key.PrivateKey;
import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
import org.bouncycastle.crypto.engines.RC2Engine;
import org.bouncycastle.crypto.modes.CBCBlockCipher;
import org.bouncycastle.pkcs.PKCS12PfxPduBuilder;
import org.bouncycastle.pkcs.PKCS12SafeBagBuilder;
import org.bouncycastle.pkcs.bc.BcPKCS12MacCalculatorBuilder;
import org.bouncycastle.pkcs.bc.BcPKCS12PBEOutputEncryptorBuilder;

/**
 * @author puddi
 */
public class Pkcs12Certificate {

    private X509Certificate certificate;
    private PrivateKey privateKey;
    private byte[] data;

    public byte[] getData() {
        return data;
    }

    public Pkcs12Certificate(X509Certificate certificate, PrivateKey privateKey) {
        this.certificate = certificate;
        this.privateKey = privateKey;
    }

    public void build(String pin) {
        var pfxPduBuilder = new PKCS12PfxPduBuilder();
        try {
            var keySafeBag = new PKCS12SafeBagBuilder(this.privateKey.getPrivateKeyInfo()).build();
            pfxPduBuilder.addEncryptedData(new BcPKCS12PBEOutputEncryptorBuilder(
                    PKCSObjectIdentifiers.pbeWithSHAAnd40BitRC2_CBC,
                    new CBCBlockCipher(new RC2Engine())
            ).build(pin.toCharArray()), keySafeBag);
            var certSafeBag = new PKCS12SafeBagBuilder(this.certificate.getBcCertificate()).build();
            pfxPduBuilder.addData(certSafeBag);
            var pfx = pfxPduBuilder.build(new BcPKCS12MacCalculatorBuilder(), pin.toCharArray());
            this.data = pfx.getEncoded();
        } catch (Exception e) {
            throw new RuntimeException("构建PKCS#12证书错误", e);
        }
    }
}
